<?php

namespace App\Http\Controllers\Common\EntityData\Video;

use App\Http\Controllers\Controller;
use App\Http\Requests\Common\EntityData\Video\ActorRequest;
use App\Models\Common\EntityData\Video\Actor;
use App\Repositories\Common\EntityData\Video\ActorRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class ActorController extends Controller
{
    use ModelForm;

    /** @var  ActorRepository */
    private $actorRepository;

    public function __construct(ActorRepository $actorRepo)
    {
        $this->actorRepository = $actorRepo;
    }

    /**
     * Display a listing of the Actor.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('common.entity_data.video.actors.index_header'));
            $content->description(__('common.entity_data.video.actors.index_description'));

            $content->body($this->grid());

            $content->row(view('entity.tag.addContentTagModal'));
        });
    }

    /**
     * Show the form for creating a new Actor.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('common.entity_data.video.actors.create_header'));
            $content->description(__('common.entity_data.video.actors.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Actor in storage.
     *
     * @param ActorRequest $request
     *
     * @return Response
     */
    public function store(ActorRequest $request)
    {
        $input = $request->all();

        $image = $request->file('avatar'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.actor');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['avatar'] = $rootDir . $fullPath;

                $input['avatar'] = $fullPath;
                $bool            = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $actor = $this->actorRepository->create($input);

        Flash::success(__('common.entity_data.video.actors.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('common.entity_data.video.actors.index'));

    }

    /**
     * Display the specified Actor.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $actor = $this->actorRepository->findWithoutFail($id);

        if (empty($actor)) {
            Flash::error(__('common.entity_data.video.actors.not_found'));

            return redirect(route('common.entity_data.video.actors.index'));
        }

        return view('common.entity_data.video.actors.show')->with('actor', $actor);

    }

    /**
     * Show the form for editing the specified Actor.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('common.entity_data.video.actors.edit_header'));
            $content->description(__('common.entity_data.video.actors.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Actor in storage.
     *
     * @param  int              $id
     * @param ActorRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $actor = $this->actorRepository->findWithoutFail($id);

        if (empty($actor)) {
            Flash::error(__('common.entity_data.video.actors.not_found'));

            return redirect(route('common.entity_data.video.actors.index'));
        }

        $input = $request->all();

        if (array_key_exists('_file_del_', $input)) {

            $imgUrl       = $actor->avatar;
            $uploadConfig = config('custom.base.upload.actor');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];

            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $actor->avatar = null;
                $actor->save();
                return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
            }

            return response()->json(['message' => '图片删除失败!', 'status' => $flag]);
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), [
            'name'       => 'required|max:100',
            'title'      => 'max:100',
            'subtitle'   => 'max:100',
            // 'avatar'     => 'max:200',
            'nickname'   => 'max:100',
            'english'    => 'max:100',
            'gender'     => 'max:10',
            'spell'      => 'max:100',
            'short_desc' => 'required|max:100',
            'birthday'   => 'date',
            'height'     => 'numeric',
            'weight'     => 'numeric',
            'area'       => 'max:100',
            'listorder'  => 'required',
        ], [
            // 'required' => ':attribute 不能为空',
        ], [
            // 'name'       => '名称',
        ]);
        
        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $image = $request->file('avatar'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                //允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.actor');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['avatar'] = $rootDir . $fullPath;

                $input['avatar'] = $fullPath;

		// 2017/08/22 modify
                // 删除原先存储的图片
                $flag = Storage::disk($driver)->delete($actor->avatar);
                
                $bool            = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $actor = $this->actorRepository->update($input, $id);

        Flash::success(__('common.entity_data.video.actors.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('common.entity_data.video.actors.index'));
    }

    /**
     * Remove the specified Actor from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->actorRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('common.entity_data.video.actors.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $actor = $this->actorRepository->findWithoutFail($id);

        if (empty($actor)) {
            Flash::error(__('common.entity_data.video.actors.not_found'));

            return redirect(route('common.entity_data.video.actors.index'));
        }

	// 2017/08/22 modify
        // $imgUrl       = $actor->avatar;
        // $uploadConfig = config('custom.base.upload.actor');
        // $driver       = $uploadConfig['driver'];
        // $dir          = $uploadConfig['dir'];
	
        // 根据配置得到根路径
        // $rootDir = config('filesystems.disks.' . $driver . '.upload');

        // $rootDir  = config('filesystems.disks.'.$driver.'.root');
        // $imgUrl = strchr($imgUrl, $rootDir);

        if ($flag = $this->actorRepository->delete($id)) {

    	    // 2017/08/22 modify
            // $bool = Storage::disk($driver)->delete($imgUrl);

            return response()->json(['message' => __('common.entity_data.video.actors.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Actor::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '演员名字')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->image('avatar', '演员头像')->removable();
            $form->text('nickname', '昵称');
            $form->text('english', '英文名称');
            $form->select('gender', '性别')->options(array(
                'male'   => '男',
                'female' => '女',
                'other'  => '其他',
            ))->default('male');
            $form->text('spell', '拼音');
            $form->text('short_desc', '简介')->help('必填');
            $form->textarea('long_desc', '详细');
            $form->date('birthday', '出生日期')->help('必填');
            $form->number('height', '身高');
            $form->number('weight', '体重');
            $form->text('area', '区域');
            $form->number('listorder', '排序');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Actor::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // //添加按钮
            // if (!\Gate::check('common.entity_data.video.actors.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('common.entity_data.video.actors.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('common.entity_data.video.actors.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('common.entity_data.video.actors.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('common.entity_data.video.actors.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            //添加按钮
            if (Admin::user()->cannot('common.entity_data.video.actors.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                //编辑按钮
                if (Admin::user()->cannot('common.entity_data.video.actors.edit')) {
                    $actions->disableEdit();
                }
                //删除按钮
                if (Admin::user()->cannot('common.entity_data.video.actors.destroy')) {
                    $actions->disableDelete();
                }
            });

            //导出按钮
            if (Admin::user()->cannot('common.entity_data.video.actors.export')) {
                $grid->disableExport();
            }

            //批量操作
            $grid->tools(function ($tools) {
                $url =  route('entity.assets.assets.model',['sp_no' => '','config_file_select'=>'']);
                $tools->append('<a href=' .$url. ' class="btn btn-sm btn-warning pull-right" title="导入数据"><i class="fa fa-ban"></i>导入数据</a>');

                $tools->batch(function ($batch) {
                    //批量删除按钮
                    if (Admin::user()->cannot('common.entity_data.video.actors.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '演员名字')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $uploadConfig = config('custom.base.upload.actor');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('avatar', '演员头像')->image($host);
            $grid->column('nickname', '昵称')->sortable();
            $grid->column('english', '英文名称')->sortable();
            $grid->column('gender', '性别')->display(function ($val) {
                switch ($val) {
                    case 'male':
                        return '男';
                        break;
                    case 'female':
                        return '女';
                    default:
                        return '其他';
                        break;
                }
            });
            $grid->column('spell', '拼音')->sortable();
            $grid->column('short_desc', '简介')->sortable();
            $grid->column('long_desc', '详细')->sortable();
            $grid->column('birthday', '出生日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('height', '身高')->sortable();
            $grid->column('weight', '体重')->sortable();
            $grid->column('area', '区域')->sortable();
            $grid->column('listorder', '排序')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 性别
                $aGenders = array(
                    'male'   => '男',
                    'female' => '女',
                    'other'  => '其他',
                );
                $filter->equal('gender', '性别')->select($aGenders);
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 英文名称
                $filter->like('english', '英文名称');
                // 地区
                $filter->like('area', '地区');
                // 拼音
                $filter->like('spell', '拼音');
                // 昵称
                $filter->like('nickname', '昵称');
                // 出生日期
                $filter->between('birthday', '出生日期')->datetime();
            });
        });
    }
}
